package com.heima.gateway.filter;

import com.heima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author: itheima
 * @create: 2022-07-28 10:56
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    /**
     * 过滤器逻辑  1.从请求头中获取令牌  2.解析令牌（判断令牌是否合法，判断令牌是否在有效期，获取令牌中载荷信息）3.
     *
     * @param exchange 封装请求对象，响应对象
     * @param chain    过滤器链（多个过滤器构成过滤器链）
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        try {
            //0.将请求白名单放行
            String path = request.getURI().getPath();
            if (path.contains("/login")) {
                return chain.filter(exchange);
            }
            //1.获取请求中令牌  企业一般设置为 authorization 作为授权头
            String token = request.getHeaders().getFirst("token");
            if (StringUtils.isNotBlank(token)) {
                //2.解析令牌 获取载荷
                Claims claimsBody = AppJwtUtil.getClaimsBody(token);
                Object userId = claimsBody.get("userId");
                Object userName = claimsBody.get("userName");
                //3.路由请求到目标微服务设置请求头：用户ID，用户名称
                request.mutate().header("userId", userId.toString());
                request.mutate().header("userName", userName.toString());
                //放行：如果存在其他过滤器则继续执行其他过滤器逻辑，如果没有：转发请求到目标微服务
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            log.error("【admin网关异常：】{}", e);
            e.printStackTrace();
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    /**
     * 过滤器执行顺序 数字越小 优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
